package com.snowj.apaas.service.impl;

import com.snowj.apaas.domain.auto.Trademark;
import com.snowj.apaas.repository.auto.AgreementsDynamicSqlSupport;
import com.snowj.apaas.repository.auto.ClientsDynamicSqlSupport;
import com.snowj.apaas.repository.auto.TrademarkDynamicSqlSupport;
import com.snowj.apaas.repository.auto.TrademarkMapper;
import com.snowj.apaas.security.SecurityConstants;
import com.snowj.apaas.security.SecurityUtils;
import com.snowj.apaas.service.TrademarkService;
import org.mybatis.dynamic.sql.SqlBuilder;
import org.mybatis.dynamic.sql.select.join.JoinCriterion;
import org.mybatis.dynamic.sql.where.condition.IsEqualTo;
import org.mybatis.dynamic.sql.where.condition.IsGreaterThanOrEqualTo;
import org.mybatis.dynamic.sql.where.condition.IsLessThanOrEqualTo;
import org.mybatis.dynamic.sql.where.condition.IsLike;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TrademarkServiceImpl implements TrademarkService  {

    private final TrademarkMapper trademarkMapper;

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public TrademarkServiceImpl(TrademarkMapper trademarkMapper) {
        this.trademarkMapper = trademarkMapper;
    }

    /**
     * 统计一年内即将到期的商标
     *
     * @return
     */
    @Override
    public long countBecomeDueTrademark() {
        Calendar calendar = Calendar.getInstance();
        Date endDate = calendar.getTime();
        calendar.add(Calendar.YEAR, -1);
        Date startDate = calendar.getTime();
        return trademarkMapper.count(c -> {
            c.where(TrademarkDynamicSqlSupport.trademarkEndtime, IsGreaterThanOrEqualTo.of(() -> startDate));
            c.where(TrademarkDynamicSqlSupport.trademarkEndtime, IsLessThanOrEqualTo.of(() -> endDate));
            return c;
        });
    }

    /**
     * 查询包括：
     * 业务员，日期（大于小于），合同编号，客户名称，商标名称，商标类别，商标号
     *
     * @param pageable
     * @return
     */
    @Override
    public Page<Trademark> listTrademarks(String salesman, String startDate, String endDate, String contractNumber,
                                          String clientName, String trademarkName, String trademarkType,
                                          String trademarkNumber, Pageable pageable) {
        List<String> authorties = SecurityUtils.getCurrentUserAuthorties();
        List<Trademark> trademarks = trademarkMapper.select(c -> {
            // 添加权限信息
            if (!authorties.contains(SecurityConstants.ROLE_ADMIN)  && !authorties.contains(SecurityConstants.ROLE_ASSISTANT)) {
                String currentUser = SecurityUtils.getCurrentUserLogin();
                c.where(TrademarkDynamicSqlSupport.salesman, IsEqualTo.of(() -> currentUser));
            }
            if (!StringUtils.isEmpty(salesman)) {
                c.where(TrademarkDynamicSqlSupport.salesman, IsLike.of(() -> "%" + salesman + "%"));
            }
            if (!StringUtils.isEmpty(startDate)) {
                try {
                    Date start = dateFormat.parse(startDate);
                    c.where(TrademarkDynamicSqlSupport.date, IsGreaterThanOrEqualTo.of(() -> start));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (!StringUtils.isEmpty(endDate)) {
                try {
                    Date end = dateFormat.parse(endDate);
                    c.where(TrademarkDynamicSqlSupport.date, IsLessThanOrEqualTo.of(() -> end));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (!StringUtils.isEmpty(contractNumber)) {
                c.where(TrademarkDynamicSqlSupport.contractNumber, IsLike.of(() -> "%" + contractNumber + "%"));
            }
            if (!StringUtils.isEmpty(clientName)) {
                c.leftJoin(ClientsDynamicSqlSupport.clients)
                        .on(TrademarkDynamicSqlSupport.clientId, SqlBuilder.equalTo(ClientsDynamicSqlSupport.id))
                        .where(ClientsDynamicSqlSupport.name, IsLike.of(() -> "%" + clientName + "%"));
            }
            if (!StringUtils.isEmpty(trademarkName)) {
                c.where(TrademarkDynamicSqlSupport.trademarkName, IsLike.of(() -> "%" + trademarkName + "%"));
            }
            if (!StringUtils.isEmpty(trademarkType)) {
                c.where(TrademarkDynamicSqlSupport.trademarkType, IsLike.of(() -> "%" + trademarkType + "%"));
            }
            if (!StringUtils.isEmpty(trademarkNumber)) {
                c.where(TrademarkDynamicSqlSupport.trademarkNumber, IsLike.of(() -> "%" + trademarkNumber + "%"));
            }
            c.offset((long) pageable.getPageSize() * pageable.getPageNumber());
            c.orderBy(TrademarkDynamicSqlSupport.trademarkEndtime.descending());
            return c.limit(pageable.getPageSize());
        });
        long total = trademarkMapper.count(c -> {
            // 添加权限信息
            if (!authorties.contains(SecurityConstants.ROLE_ADMIN)  && !authorties.contains(SecurityConstants.ROLE_ASSISTANT)) {
                String currentUser = SecurityUtils.getCurrentUserLogin();
                c.where(TrademarkDynamicSqlSupport.salesman, IsEqualTo.of(() -> currentUser));
            }
            if (!StringUtils.isEmpty(salesman)) {
                c.where(TrademarkDynamicSqlSupport.salesman, IsLike.of(() -> "%" + salesman + "%"));
            }
            if (!StringUtils.isEmpty(startDate)) {
                try {
                    Date start = dateFormat.parse(startDate);
                    c.where(TrademarkDynamicSqlSupport.date, IsGreaterThanOrEqualTo.of(() -> start));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (!StringUtils.isEmpty(endDate)) {
                try {
                    Date end = dateFormat.parse(endDate);
                    c.where(TrademarkDynamicSqlSupport.date, IsLessThanOrEqualTo.of(() -> end));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (!StringUtils.isEmpty(contractNumber)) {
                c.where(TrademarkDynamicSqlSupport.contractNumber, IsLike.of(() -> "%" + contractNumber + "%"));
            }
            if (!StringUtils.isEmpty(clientName)) {
                JoinCriterion joinCriterion = new JoinCriterion.Builder()
                        .withJoinColumn(TrademarkDynamicSqlSupport.clientId)
                        .withConnector("on")
                        .withJoinCondition(SqlBuilder.equalTo(ClientsDynamicSqlSupport.id)).build();
                c.leftJoin(ClientsDynamicSqlSupport.clients, joinCriterion)
                        .where(ClientsDynamicSqlSupport.name, IsLike.of(() -> "%" + clientName + "%"));
            }
            if (!StringUtils.isEmpty(trademarkName)) {
                c.where(TrademarkDynamicSqlSupport.trademarkName, IsLike.of(() -> "%" + trademarkName + "%"));
            }
            if (!StringUtils.isEmpty(trademarkType)) {
                c.where(TrademarkDynamicSqlSupport.trademarkType, IsLike.of(() -> "%" + trademarkType + "%"));
            }
            if (!StringUtils.isEmpty(trademarkNumber)) {
                c.where(TrademarkDynamicSqlSupport.trademarkNumber, IsLike.of(() -> "%" + trademarkNumber + "%"));
            }
            return c;
        });
        return new PageImpl<>(trademarks, pageable, total);
    }

    /**
     * 根据编号查询商标
     *
     * @param id 商标编号
     * @return
     */
    @Override
    public Optional<Trademark> findTrademark(Long id) {
        List<String> authorties = SecurityUtils.getCurrentUserAuthorties();
        // 添加权限信息
        if (!authorties.contains(SecurityConstants.ROLE_ADMIN)  && !authorties.contains(SecurityConstants.ROLE_ASSISTANT)) {
            return trademarkMapper.selectOne(c -> {
                String currentUser = SecurityUtils.getCurrentUserLogin();
                c.where(TrademarkDynamicSqlSupport.salesman, IsEqualTo.of(() -> currentUser));
                c.where(TrademarkDynamicSqlSupport.id, IsEqualTo.of(() -> id));
                return c;
            });
        } else {
            return trademarkMapper.selectByPrimaryKey(id);
        }
    }

    /**
     * 创建商标
     *
     * @param trademark
     * @return
     */
    @Override
    public Trademark createTrademark(Trademark trademark) {
        if (trademark.getId() != null) {
            return null;
        }
        trademark.setCreatedBy(SecurityUtils.getCurrentUserLogin());
        trademark.setCreatedDate(new Date());
        trademarkMapper.insert(trademark);
        return trademark;
    }

    /**
     * 更新商标
     *
     * @param trademark
     * @return
     */
    @Override
    public Trademark updateTrademark(Trademark trademark) {
        if (trademark.getId() == null) {
            return null;
        }
        Optional<Trademark> savedTrademarkOptional = trademarkMapper.selectByPrimaryKey(trademark.getId());
        if (savedTrademarkOptional.isPresent()) {
            Trademark savedTrademark = savedTrademarkOptional.get();
            trademark.setCreatedBy(savedTrademark.getCreatedBy());
            trademark.setCreatedDate(savedTrademark.getCreatedDate());
            trademark.setLastModifiedBy(SecurityUtils.getCurrentUserLogin());
            trademark.setLastModifiedDate(new Date());
            trademarkMapper.updateByPrimaryKey(trademark);
            return trademark;
        } else {
            return null;
        }
    }

    /**
     * 删除商标
     *
     * @param id 商标编号
     */
    @Override
    public void deleteTradeMark(Long id) {
        trademarkMapper.deleteByPrimaryKey(id);
    }
}
